<?php

namespace plugin\admin\app\model;

use plugin\admin\app\model\Base;

/**
 * @property integer $id (主键)
 * @property string $name 商品分类
 * @property string $mobile_show_name 手机显示名称
 * @property integer $is_recommend 是否推荐
 * @property integer $is_show 是否显示
 * @property integer $sort 排序
 */
class GoodsCategory extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_goods_categories';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;


    public static function list()
    {
        $data = self::all()->toArray();

        $newData = [];

        foreach ($data as $key=>$value) {
            $newData[] = ['name' => $value['name'], 'value' => $value['id']];
        }

        return $newData;
    }

    public static function getTree($backend = true)
    {
        $data = self::select(['id', 'pid', 'name', 'thumb'])->orderBy('sort')->get()->toArray();

        if ($backend) {
            foreach ($data as $key=>$value) {
                $data[$key]['value'] = $value['id'];
            }
        }


        return self::buildTree($data);
    }

    public static function buildTree($categories, $parent_id = 0) {
        $tree = array();

        foreach ($categories as $category) {
            $category['thumb'] = full_url($category['thumb']);
            if ($category['pid'] == $parent_id) {
                $children = self::buildTree($categories, $category['id']);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }

        return $tree;
    }
}
